package com.study.app.controller;


import com.alibaba.fastjson.JSONObject;

import com.study.app.FileUtils;
import com.study.app.entity.FileModel;
import com.study.app.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/business/file")
public class FileController {
    private IFileService fileService;
    private FileUtils fileUtils;

    @Autowired
    public FileController(IFileService fileService, FileUtils fileUtils) {
        this.fileService = fileService;
        this.fileUtils = fileUtils;
    }
    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestParam(value = "file") MultipartFile[] files){
        log.info("上次文件数量{}",files.length);
        JSONObject jsonObject = new JSONObject();
        if (files.length == 1){
            FileModel fileObj = fileUtils.getFile(files[0]);
            boolean flag = fileService.save(fileObj);
            if (flag){

                jsonObject.put("url",fileObj.getFileId());
                jsonObject.put("alt","213");
                jsonObject.put("href","1231");
                return jsonObject;
            }
        }
        return jsonObject;
    }

    @GetMapping("/lookFile")
    public void downloadFile(@RequestParam String fileId) {
        FileModel blogFile = fileService.getById(fileId);
        String fileLocation = blogFile.getFileLocation();
        fileUtils.downloadFile(fileLocation);
    }

}
